/**
 * @desc:任务中心
 * @author: fj
 */
import { useState, useMemo, useEffect } from 'react';
import FormRender from '@/components/FormRender';
import TableRender from '@/components/TableRender';
import { useResize } from '@/hooks/useResize';
import { getFormItem } from './config/form.js';
import { getColumns } from './config/columns.jsx';
import { httpChange, GetChinese } from '@/utils/utils.jsx';
import { message } from 'antd';
import moment from 'moment';
import { getTableListOp, deleteExportTask, downLoadFileOp } from './service.js';

const initQuery = {
  time: [moment().startOf('month'), moment().endOf('month')]
}

const TaskCenter = () => {

  const [query, setQuery] = useState({ ...initQuery });

  const [data, setData] = useState([]);

  const [pages, setPages] = useState({
    current: 1,
    total: 0,
    pageSize: 100,
  }); //分页数据

  //监听变更
  const { el: headerEl, height: headerHeight } = useResize();

  useEffect(() => {
    getTaskList();
  }, [query, pages.current, pages.pageSize])


  //获取任务列表
  const getTaskList = async () => {
    const params = {
      ...query,
      size: pages.pageSize,
      current: pages.current,
    };
    if (params.time) {
      params.startTime = moment(params.time[0]).format('YYYY-MM-DD HH:mm:ss');
      params.endTime = moment(params.time[1]).format('YYYY-MM-DD HH:mm:ss');
    }
    params.time = undefined;
    START_LOADING();
    const { success, data } = await getTableListOp(params);
    END_LOADING();
    if (success) {
      const { records = [], total } = data;
      setData(records);
      setPages({
        ...pages,
        total
      })
    }
  };

  //删除任务
  const deleteFunc = async (ids) => {
    START_LOADING();
    const { success } = await deleteExportTask({ ids });
    if (success) {
      message.success('导出任务成功删除！');
      getTaskList();
    }
    END_LOADING();
  };

  //点击导出
  const handleClickExport = async (id) => {
    START_LOADING();
    const { data, success } = await downLoadFileOp({ id });
    if (success) {
      message.success('浏览器下载中，请稍后');
      getTaskList();
      exportFile(data);
    }
    END_LOADING();
  };

  //导出文件
  const exportFile = (url) => {
    fetch(httpChange(url), {
      method: 'GET',
    })
      .then((res) => res.blob())
      .then((data) => {
        const blobUrl = window.URL.createObjectURL(data);
        const a = document.createElement('a');
        a.download = GetChinese(url) + '.xlsx';
        a.href = httpChange(blobUrl);
        a.click();
      });
  };

  const handleOpera = (type, val) => {
    if(type == 'delete') {
      deleteFunc(val);
    } else if(type == 'export') {
      handleClickExport(val)
    }
  }

  //表单数据
  const formArr = useMemo(() => {
    return getFormItem();
  }, [])


  const columns = useMemo(() => {
    return getColumns({ handleOpera })
  }, [])

  //表单渲染组件
  const FormRenderProps = {
    query,
    formArr,
    formConfig: {
      name: 'task-center-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      pages.current = 1;
      setPages(pages);
      setQuery(val);
    },
    clickReset() {
      pages.current = 1;
      setQuery({ ...initQuery });
    },
  }

  //表格组件
  const TableRenderProps = {
    data,
    columns,
    style: {
      height: `calc(100vh - ${headerHeight + 184}px)`
    },
    pageConfig: {
      pages,
      handlePageSize(page, size) {
        setPages({
          ...pages,
          current: page,
          pageSize: size
        });
      }
    }
  }

  return (
    <>
      <div ref={headerEl}>
        <FormRender {...FormRenderProps} />
      </div>
      <div className='global-page-wrap'>
        <TableRender {...TableRenderProps} />
      </div>
    </>
  );
};

export default TaskCenter;